<?php
/**
 * Created by PhpStorm.
 * User: sunwu
 * Date: 2018/2/7
 * Time: 14:49
 */

namespace app\home\controller;

use app\home\def\Helper;
use app\home\def\Status;
use app\home\model\Collection;
use app\home\model\Resource;
use app\home\model\ResourceCategory;
use app\home\model\User as userModel;
use app\home\model\Comment as CommentModel;
use app\home\model\UserPaid;
use think\console\command\Help;
use think\Db;
use think\Url;

class User extends Base
{
    private $userModel;//用户模型
    private $commentModel;//评论模型
    private $catModel;
    private $resModel;
    private $collModel;
    private $paidModel;
    private $uid;//用户的pid

    public function __construct()
    {
        parent::__construct();
        Url::root('/index.php');//携带入口文件
        $this->checkIsLogin();//检查是否登录
        $this->uid = session('uid');//初始化uid
        $this->userModel = new userModel();
        $this->commentModel = new CommentModel();
        $this->catModel = new ResourceCategory();
        $this->resModel = new Resource();
        $this->collModel = new Collection();
        $this->paidModel=new UserPaid();


    }

    private function getUserInfo($guid = '')
    {
        //用户信息
        if (!$guid) {
            $userinfo = $this->userModel->getUserInfo();
            $this->assign('i', $userinfo);
        } else {
            //具体用户的信息
            $userinfo = $this->userModel->getUserInfo($guid);
            $this->assign('i', $userinfo);
        }

    }

    /**
     * 签到
     */
    public function reports()
    {
        //todo 添加签到判断条件
        $res1 = $this->userModel->where('PK_UserGuid', $this->uid)->setInc('reports', 1);
        $res2 = $this->userModel->where('PK_UserGuid', $this->uid)->setInc('Gold', 1);
        $res3 = $this->userModel->where('PK_UserGuid', $this->uid)->update(['last_reports' => time()]);
        if ($res1 > 0 && $res2 > 0) {
            $this->setSessionReports(session('ureports') + 1);

            return $this->err->info(0);
        } else {
            return $this->err->info(1);
        }
    }

    /**
     * 用户主页
     * @return \think\response\View
     */
    public function home()
    {
        $this->getUserInfo();

        return view();
    }

    public function user()
    {
        $this->getUserInfo();

        return view();
    }

    public function set()
    {
        $this->getUserInfo();

        return view();
    }

    /**
     * 废弃 图像上传测试
     * @return \think\response\View
     */
    public function upload()
    {
        return view();
    }

    /**
     * 修改基本信息
     */
    public function setBaseInfo()
    {
        return $this->res();
    }

    /**
     * 修改密码
     * @return array
     */
    public function setPwd()
    {
        $oldPwd = input('post.nowpwd');
        if ($oldPwd !== session('upwd')) return $this->err->info(10002);
        $pwd = input('post.pwd');
        $repwd = input('post.repwd');
        if ($pwd === $repwd) {
            $res = $this->userModel->where('PK_UserGuid', $this->uid)->update(['password' => $pwd]);
            if ($res > 0) {
                $this->setSessionPwd($pwd);

                return $this->err->info(0);
            }
            if ($res == 0) return $this->err->info(1);

            return $this->err->info(-1);
        } else {
            return $this->err->info(10001);
        }
    }

    /**
     * 设置封面
     */
    public function setCover()
    {
        return $this->res();
    }

    /**
     * 更新数据 一次性更新
     * @return array
     */
    private function res()
    {
        $res = $this->userModel->where('PK_UserGuid', $this->uid)->update(input('post.'));
        if ($res > 0) {
            $name = input('post.Name');
            $ucover = input('post.Cover');
            if ($name) $this->setSessionName($name);
            if ($ucover) $this->setSessionCover($ucover);

            return $this->err->info(0);
        }
        if ($res == 0) return $this->err->info(1);

        return $this->err->info(-1);
    }

    /**
     * 更新name
     *
     * @param $name
     */
    private function setSessionName($name)
    {
        session('name', $name);
    }

    /**
     * 更新头像
     *
     * @param $cover
     */
    private function setSessionCover($cover)
    {
        session('ucover', $cover);
    }

    /**
     * 更新密码
     *
     * @param $pwd
     */
    private function setSessionPwd($pwd)
    {
        session('upwd', $pwd);
    }

    /**
     * 更新签到天数
     *
     * @param $reports
     */
    private function setSessionReports($reports)
    {
        session('ureports', $reports);
    }

    /**
     * 评论
     */
    public function rescomment()
    {
        $resguid = input('post.resguid');
        if (!$resguid) return $this->err->info(11001);
        $comment = input('post.comment');
        $commentguid = md5(rand());
        $res = $this->commentModel->save(['PK_CommentGuid' => $commentguid, 'FK_ResourceGuid' => $resguid, 'FK_UserGuid' => $this->uid, 'comment' => $comment, 'status' => '可用',]);
        if ($res > 0) return $this->err->info(0);
    }

    /**
     * 顶一下
     * @return array
     */
    public function tops()
    {
        $resguid = input('post.guid');
        $res = Db::table('rs_resource')->where('PK_ResourceGuid', $resguid)->setInc('Tops');
        if ($res > 0) {
            return $this->err->info(0);
        } else if ($res === 0) {
            return $this->err->info(1);
        } else {
            return $this->err->info(-1);
        }
    }


    /**
     * 资源详情工具栏
     * type='unstart'时的guid是collectio的guid
     * @param $guid
     * @param $type
     */
    public function resDetailToolsApi($guid = 'guid', $type = 'type')
    {
        $dbStatus = -1;
        switch ($type) {
            case "start": {
                $colGuid = $this->collModel->where(['FK_UserGuid' => $this->uid, 'FK_ResourceGuid' => $guid])->value('PK_CollectionGuid');

                if ($colGuid) {
                    $dbStatus = $this->collModel->save(['Status' => '可用'],
                        [
                            'PK_CollectionGuid' => $colGuid
                        ]);

                } else {
                    $dbStatus = $this->collModel->save([
                        'PK_CollectionGuid' => get_guid(),
                        'FK_UserGuid' => $this->uid,
                        'FK_ResourceGuid' => $guid,
                        'Status' => '可用'
                    ]);
                }

            }
                break;
            case "unstart": {
                $dbStatus = $this->collModel->save(['Status' => '不可用'],
                    [
                        'FK_UserGuid' => $this->uid,
                        'FK_ResourceGuid' => $guid
                    ]);
            }
                break;
            case "top": {
                $dbStatus = Db::table('rs_resource')->where('PK_ResourceGuid', $guid)->setInc('Tops');
            }
                break;
            case "untop": {
                $dbStatus = Db::table('rs_resource')->where('PK_ResourceGuid', $guid)->setDec('Tops');
            }
                break;
            default: {
            }
                break;

        }
        if ($dbStatus > 0) {
            return $this->err->info(0);
        } else if ($dbStatus === 0) {
            return $this->err->info(1);
        } else {
            return $this->err->info(-1);
        }
    }

    /**
     * 分享(添加|新增)资源
     */
    public function share()
    {
        //将分类赋值
        $catsModel = new ResourceCategory();
        $cats = $catsModel->where(Status::$able)->select();
        $this->assign('cats', $cats);//分类数据

        $this->assign('rt', Status::$resType);//资源类型
        $this->assign('pri', Status::$price);//价格
        $resModel = new Resource();

        //获取数据
        $resData = input('post.');
        $vercode = input('post.vercode');
        if ($resData) {
            if ($this->checkVercode($vercode, 'share')) {
                //验证码正确
                $resData['PK_ResourceGuid'] = get_guid();
                $resData['FK_UserGuid'] = $this->uid;
                //当前用户是否是管理员,如果是的话,不用审核发表的资源
                if($this->isAllowUsr()){
                    $resData['Status'] = '已审核';
                }else{
                    $resData['Status'] = '未审核';
                }
                $res = $resModel->allowField(true)->save($resData);
                if ($res > 0) {
                    return $this->err->info(0);
                } else {
                    return $this->err->info(-1);
                }
            } else {
                die('非法操作');
            }

        } else {
            return view();
        }

    }

    public function modifyShare($guid = '')
    {
        $this->checkUserIsCanModifyShare($guid);
        $this->assign('price', Status::$price);
        $this->assign('resType', Status::$resType);
        $this->assign('cats', $this->catModel->select());
        $this->assign('res', $this->resModel->find($guid));

        return view();
    }


    public function modifyShareApi()
    {
        /*
         * FK_ResourceCategoryGuid:d15c19b0bd1c0ec29f807c2b8ad84cb2
            Title:模板引擎文档 - layui.laytpl
            type:文本资源
            panurl:
            panpwd:
            weburl:
            Desc:layui官网: a(http://www.layui.com/doc/modules/laytpl.html)[http://www.layui.com/doc/modules/laytpl.html]
            Price:1
            vercode:v2df
         */

//        if (!Helper::checkVercode(input('post.vercode'), 'modifyShare')) return $this->err->info(2);

        return $this->err->resUpdata($this->resModel->allowField(true)->save(input('post.'), ['PK_ResourceGuid' => input('post.PK_ResourceGuid')]));
    }

    /**
     * 修改
     */
    public function modify()
    {
        return view();
    }


    /**
     * 用户信息信息
     */
    public function userDetail($guid = '')
    {
        $this->getUserInfo($guid);

        return view();
    }

    /**
     * 检查用户是否有有权限修改资源|只有发的人才能更改
     *
     * @param $guid
     */
    private function checkUserIsCanModifyShare($guid)
    {
        $userGuid = $this->resModel->where("PK_ResourceGuid", $guid)->value('FK_UserGuid');
        if ($this->uid !== $userGuid) {
            $this->error('只有发帖人才能编辑');
            exit;
        }
    }

    public function pageTest()
    {
        /*			   $userInfo=self::with(['collection','resource','recomment','collection.resource','recomment.resource','downloads','downloads.resource'])->find($userId);
                    $this->getUserInfo();
                     查询状态为1的用户数据 并且每页显示10条数据
                    $list = $this->resModel->with(['collection','resource','recomment','collection.resource','recomment.resource','downloads','downloads.resource'])->paginate(10);

                    var_dump($list);
                    // 把分页数据赋值给模板变量list
                    $this->assign('list' , $list);
        //			$this->assign('i',$list['data']);

                    // 渲染模板输出
                    return $this->fetch();*/
        return view();


    }

    /**
     * 获取资源的收藏的guid
     */
    public function resCollStatus($guid = 'guid')
    {
        return $this->err->info(0, $this->collModel->where([
            'FK_ResourceGuid' => $guid,
            'FK_UserGuid' => $this->uid
        ])->value('Status'));
    }


    public function delCollApi($guid = '')
    {
        return $this->err->info(0, Collection::destroy($guid));
    }

    /**
     * 获取资源的附件|即资源关键的东西
     */
    public function attachement($guid='')
    {
        return view();
    }

    /**当前用户是否为管理员
     * @return bool
     */
    private function isAllowUsr()
    {
        $allowUsr=(new Audit())->getAllowUsr();
        if(in_array($this->uid,$allowUsr)){
            return true;
        }return false;
    }


    /**
     * 查询资源是否支付
     * 未支付:false
     * 支付了:返回资源的详细信息
     * @param $res_guid
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function resIsPaidApi($res_guid)
    {
        $paid=$this->paidModel->with('resource')->where([
            'fk_user_guid'=>$this->uid,
            'fk_resource_guid'=>$res_guid
        ])->find();
        if(empty($paid)){
            return $this->err->info(5);
        }else{
            return $this->err->info(0,$paid['resource']);
        }
    }

    public function resPaidApi($res_guid)
    {
        $gold=$this->userModel->where('PK_UserGuid',$this->uid)->value('Gold');
        if($gold>0){
            $data=[
                'pk_user_paid_guid'=>get_guid(),
                'fk_user_guid'=>$this->uid,
                'fk_resource_guid'=>$res_guid
            ];
            Db::table('rs_user')->where('PK_UserGuid', $this->uid)->setDec('Gold');
            return $this->err->resAdd($this->paidModel->save($data));
        }else{
            return $this->err->info(13001);
        }


    }
}